<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1100px">
    <el-form :model="formData" ref="formRef" :rules="formRules" vloading="formLoading">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="elderName">
            <el-input v-model="formData.elderName" disabled class="mr-1" />
            <el-button @click="clickChooseElder">选择老人</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用药时间" prop="useTime">
            <el-date-picker
              v-model="formData.useTime"
              placeholder="请输入用药时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              :clearable="true"
              type="datetime"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <Table
      :columns="columns"
      :adaptive="true"
      :data="formData.details"
      save-key="HealthMedicineRegisterPlan"
      :row-style="rowStyle"
      @row-click="handleRowClick"
    >
      <template #check="{ row }">
        <el-checkbox v-model="row.check" />
      </template>
      <template #medicineType="{ row }">
        {{ getDictObj(DICT_TYPE.HEALTH_MEDICINE_TYPE, row.medicine.medicineType).label }}
      </template>
      <template #medicineDosageForm="{ row }">
        {{
          getDictObj(DICT_TYPE.HEALTH_MEDICINE_DOSAGE_FORM, row.medicine.medicineDosageForm).label
        }}
      </template>
    </Table>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <HealthMedicinePlanSelect ref="medicinePlanSelectRef" @row-dblclick="handleSelectMedicinePlan" />
</template>
<script setup name="HealthMedicineRegisterPlan" lang="ts">
import { DICT_TYPE, getDictObj } from '@/utils/dict'
import HealthMedicinePlanSelect from '../healthMedicinePlan/HealthMedicinePlanSelect.vue'
import * as HealthMedicineRegisterApi from '@/api/health/medicineRegister'
import * as HealthMedicinePlanApi from '@/api/health/medicinePlan'
import * as HealthMedicinePlanDetailModel from '@/model/health/medicine/HealthMedicinePlanDetail'
interface HealthMedicineRegisterPlanModeDetail
  extends HealthMedicinePlanDetailModel.HealthMedicinePlanDetail {
  medicine: {
    medicineName: string
    medicineBrevityCode: string
    medicineType: string
    medicineSpecification: string
    medicineDosageForm: string
  }
  check: boolean
}
interface HealthMedicineRegisterPlanMode {
  elderId: string
  elderName: string
  useTime: string
  details: HealthMedicineRegisterPlanModeDetail[]
}
const dialogTitle = ref('')
const dialogVisible = ref(false)
const medicinePlanSelectRef = ref()
const { t } = useI18n()
const message = useMessage()
const formRef = ref()
const formLoading = ref(false)
const formData = ref<HealthMedicineRegisterPlanMode>({
  elderId: '',
  elderName: '',
  useTime: '',
  details: []
})
const formRules = reactive({
  name: [{ required: true, message: '请输入姓名', trigger: 'change' }],
  useTime: [{ required: true, message: '请输入用药时间', trigger: 'change' }]
})
const tableCurrentRow = ref()
const columns = [
  {
    label: '选中',
    prop: 'check',
    slot: 'check'
  },
  {
    label: '药品名称',
    prop: 'medicine.medicineName'
  },
  {
    label: '药品简码',
    prop: 'medicine.medicineBrevityCode'
  },
  {
    label: '药品类型',
    prop: 'medicine.medicineType',
    slot: 'medicineType'
  },
  {
    label: '药品规格',
    prop: 'medicine.medicineSpecification'
  },
  {
    label: '药品剂型',
    prop: 'medicine.medicineDosageForm',
    slot: 'medicineDosageForm'
  },
  {
    label: '天频率',
    prop: 'dayRate'
  },
  {
    label: '次频率',
    prop: 'timeRate'
  },
  {
    label: '用药数量',
    prop: 'number'
  },
  {
    label: '备注',
    prop: 'remark'
  },
  {
    label: '上次用药时间',
    prop: 'lastUseTime'
  }
]
/** 打开弹窗 */
const open = () => {
  dialogVisible.value = true
  resetForm()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    elderId: '',
    elderName: '',
    useTime: '',
    details: []
  }
  formRef.value?.resetFields()
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const planIds: (number | undefined)[] = []
    formData.value.details.forEach((detail) => {
      if (detail.check == true) planIds.push(detail.id)
    })
    const data = { useTime: formData.value.useTime, planDetailIds: planIds }
    await HealthMedicineRegisterApi.planCreate(data)
    message.success(t('common.createSuccess'))
    dialogVisible.value = false
  } finally {
    formLoading.value = false
  }
  emit('success')
}

/** table行的style的回调方法 */
const rowStyle = ({ row }) => {
  if (row?.operateType == 'delete') {
    return { display: 'none' }
  } else return {}
}

/** table行点击事件 */
const handleRowClick = (row) => {
  tableCurrentRow.value = row
}

const clickChooseElder = () => {
  medicinePlanSelectRef.value.open()
}

const handleSelectMedicinePlan = async (selectPlanInfo) => {
  formData.value.elderName = selectPlanInfo.elder.name
  formData.value.elderId = selectPlanInfo.elderId
  const planInfo = await HealthMedicinePlanApi.singleGet(selectPlanInfo.id)
  formData.value.details = planInfo.details
  formData.value.details.forEach((detail) => {
    detail.check = true
  })
}
</script>
